package com.etc.threaddemo;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author: knowno
 * @create: 2024-09-13 09:16
 * @Version 1.0
 * 2. 线程的实现方式3，实现Callable接口，重写call方法.
 * 方法带返回值
 **/
public class TestCallable {
    public static void main(String[] args) {


        MyCallable myCallable = new MyCallable();
        //我們要將callable对象交给FutrueTask来管理
        FutureTask futureTask = new FutureTask<>(myCallable);
        //创建一个thread对象
        //RunnableFuture<V> extends Runnable
        //FutureTask<V> implements RunnableFuture
        Thread thread = new Thread(futureTask);

        thread.start();

        //获取返回值
        Object o = null;
        try {
            o = futureTask.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        System.out.println(o);

    }
}

class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {

        int sum = 0;
        for (int i = 0; i < 10; i++) {
            sum += i;
            System.out.println(Thread.currentThread().getId() + "," + Thread.currentThread().getName());
        }
        return sum + "";
    }
}
